package com.keba.lamp.complaint.service.impl;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.metadata.Head;
import com.alibaba.excel.write.handler.CellWriteHandler;
import com.alibaba.excel.write.handler.context.CellWriteHandlerContext;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.metadata.holder.WriteSheetHolder;
import com.alibaba.excel.write.metadata.holder.WriteTableHolder;
import com.google.common.collect.Lists;
import com.keba.basic.base.service.impl.SuperServiceImpl;
import com.keba.lamp.complaint.entity.AccountDetail;
import com.keba.lamp.complaint.manager.AccountDetailManager;
import com.keba.lamp.complaint.service.AccountDetailService;
import com.keba.lamp.complaint.vo.result.AccountPrepaymentExportVO;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 业务实现类
 * 账户明细
 * </p>
 *
 * @author twg
 * @date 2025-05-15 20:30:52
 * @create [2025-05-15 20:30:52] [twg] [代码生成器生成]
 */
@Slf4j
@RequiredArgsConstructor
@Service
@Transactional(readOnly = true)
public class AccountDetailServiceImpl extends SuperServiceImpl<AccountDetailManager, Long, AccountDetail> implements AccountDetailService {

    /**
     * 填充excel
     *
     * @param vo
     * @param response
     */
    @Override
    public void fillDayExcel(AccountPrepaymentExportVO vo, HttpServletResponse response) throws IOException {
        ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream())
                .registerWriteHandler(new CustomCellWriteHandler()) // 自定义列宽处理器
                .needHead(true)
                .build();
        WriteSheet writeSheet = EasyExcel.writerSheet("账单").build();
        List<List<String>> firstLine = Lists.newArrayList();
        firstLine.add(Lists.newArrayList("#账务明细查询（单位：元）"));
        excelWriter.write(firstLine, writeSheet);
        List<List<String>> secondLine = Lists.newArrayList();
        secondLine.add(Lists.newArrayList("#账户名称：" + vo.getName()));
        excelWriter.write(secondLine, writeSheet);
        List<List<String>> afFirstLine = Lists.newArrayList();
        afFirstLine.add(Lists.newArrayList("#账户编码：" + vo.getCode()));
        excelWriter.write(afFirstLine, writeSheet);
        List<List<String>> afSecondLine = Lists.newArrayList();
//        String startTime = Objects.isNull(vo.getStartTime()) ? "" : DateUtil.format(vo.getStartTime(), DatePattern.NORM_DATETIME_FORMATTER);
//        String endTime = Objects.isNull(vo.getEndTime()) ? "" : DateUtil.format(vo.getEndTime(), DatePattern.NORM_DATETIME_FORMATTER);
        afSecondLine.add(Lists.newArrayList("#起始日期：" + vo.getStartTime() + "  终止日期：" + vo.getEndTime()));
        excelWriter.write(afSecondLine, writeSheet);

        List<List<String>> fourLine = Lists.newArrayList();
        fourLine.add(Lists.newArrayList("类型", "业务类别", "下单时间", "名称" , "案件编号", "账户流水号", "账户类型",
                "收支类型", "金额", "预付款余额", "下单时间", "入账时间", "备注"));
        excelWriter.write(fourLine, writeSheet);
        vo.getDataList().forEach(p ->
                excelWriter.write(Lists.newArrayList(p), writeSheet)
        );
        List<List<String>> thirdLine = Lists.newArrayList();
        thirdLine.add(Lists.newArrayList("#-----------------------------------------业务明细列表----------------------------------------"));
        excelWriter.write(thirdLine, writeSheet);

        List<List<String>> sumFeeLine = Lists.newArrayList();
        sumFeeLine.add(Lists.newArrayList("合计费用：" + vo.getTotalPayAmount()));
        excelWriter.write(sumFeeLine, writeSheet);

        List<List<String>> applyTimeLine = Lists.newArrayList();
        applyTimeLine.add(Lists.newArrayList("申请导出时间：[" + DateUtil.format(new Date(), DatePattern.NORM_DATETIME_FORMATTER) + "]"));
        excelWriter.write(applyTimeLine, writeSheet);
        excelWriter.finish();
    }

    public class CustomCellWriteHandler implements CellWriteHandler {

        // 存储列索引和对应的列宽
        private Map<Integer, Integer> columnWidthMap = new HashMap<>();

        public CustomCellWriteHandler() {
            // 设置各列的宽度（单位为字符宽度）
            columnWidthMap.put(0, 10);
            columnWidthMap.put(1, 10);
            columnWidthMap.put(2, 20);
            columnWidthMap.put(3, 10);
            columnWidthMap.put(4, 20);
            columnWidthMap.put(5, 20);
            columnWidthMap.put(6, 12);
            columnWidthMap.put(7, 10);
            columnWidthMap.put(8, 10);
            columnWidthMap.put(9, 10);
            columnWidthMap.put(10, 20);
            columnWidthMap.put(11, 20);
            columnWidthMap.put(12, 10);
        }

        @Override
        public void beforeCellCreate(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder,
                                     Row row, Head head, Integer integer, Integer integer1, Boolean aBoolean) {
            // 单元格创建前的处理
        }

        @Override
        public void afterCellCreate(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder,
                                    Cell cell, Head head, Integer integer, Boolean aBoolean) {
            // 单元格创建后的处理
        }

        @Override
        public void afterCellDispose(CellWriteHandlerContext context) {
            // 单元格处理完成后的处理
            Sheet sheet = context.getWriteSheetHolder().getSheet();
            int columnIndex = context.getCell().getColumnIndex();

            // 如果该列有设置宽度，则应用
            if (columnWidthMap.containsKey(columnIndex)) {
                // Excel列宽单位转换：POI中列宽单位为1/256个字符宽度
                sheet.setColumnWidth(columnIndex, columnWidthMap.get(columnIndex) * 256);
            }
        }
    }
}


